#pragma once
#include "abstract.hpp"
#include "muduo/net/TcpServer.h"
#include "muduo/net/EventLoop.h"
#include "muduo/base/CountDownLatch.h"
#include "muduo/net/EventLoopThread.h"
#include "muduo/net/TcpClient.h"
#include "muduo/net/Buffer.h"
#include "message.hpp"
#include "logger.hpp"
#include <mutex>
#include <functional>
/*
    网络模块封装
*/
namespace rpc
{
    class MuduoBuffer : public BaseBuffer
    {
    private:
        muduo::net::Buffer *_buf;

    public:
        using ptr = std::shared_ptr<MuduoBuffer>;
        MuduoBuffer(muduo::net::Buffer *buf) : _buf(buf) {}
        virtual size_t readableSize() override
        {
            return _buf->readableBytes();
        }
        virtual int32_t peekInt32() override
        {
            return _buf->peekInt32();
        }
        virtual void retrieveInt32() override
        {
            return _buf->retrieveInt32();
        }
        virtual int32_t readInt32() override
        {
            return _buf->readInt32();
        }
        virtual std::string retrieveAsString(size_t len) override
        {
            return _buf->retrieveAsString(len);
        }
    };

    class BufferFactory
    {
    public:
        template <typename... Args>
        static BaseBuffer::ptr create(Args &&...args)
        {
            return std::make_shared<MuduoBuffer>(std::forward<Args>(args)...);
        }
    };

    class LVProtocol : public BaseProtocol
    {
    private:
        const size_t lenFieldsLength = 4;
        const size_t mtypeFieldsLength = 4;
        const size_t idlenFieldsLength = 4;

    public:
        using ptr = std::shared_ptr<LVProtocol>;
        /*
            |--Len--|--VALUE--|
            |--Len--|--mtype--|--idlen--|--id--|--body--|
            尝试是否够一个message
        */
        virtual bool canProcessed(const BaseBuffer::ptr &buf) override
        {
            if (buf->readableSize() < lenFieldsLength)
            {
                return false;
            }
            int32_t bufLen = buf->peekInt32();
            if (buf->readableSize() < (bufLen + lenFieldsLength))
            {
                return false;
            }
            return true;
        }
        /*
            |--Len--|--VALUE--|
            |--Len--|--mtype--|--idlen--|--id--|--body--|
            获取message
        */
        virtual bool onMessage(const BaseBuffer::ptr &buf, BaseMessage::ptr &msg) override
        {
            // Len
            int32_t bufLen = buf->readInt32();
            // mtype
            MType type = (MType)buf->readInt32();
            // idlen
            int32_t idLen = buf->readInt32();
            // id
            std::string id = buf->retrieveAsString(idLen);
            // body
            int32_t bodyLen = bufLen - mtypeFieldsLength - idlenFieldsLength - idLen;
            std::string body = buf->retrieveAsString(bodyLen);

            msg = MessageFactory::create(type);
            if (msg.get() == nullptr)
            {
                LOG(ERROR, "消息类型错误，构造消息对象失败！");
                return false;
            }
            bool ret = msg->unserialize(body);
            if (ret == false)
            {
                LOG(ERROR, "消息正文反序列化失败！");
                return false;
            }
            msg->setId(id);
            msg->setMType(type);
            return true;
        }

        virtual std::string serialize(const BaseMessage::ptr &msg) override
        {
            std::string body = msg->serialize();
            std::string id = msg->rid();
            auto mtype = htonl((int32_t)msg->mtype());
            int32_t idlen = htonl(id.size());
            int32_t h_total_len = mtypeFieldsLength + idlenFieldsLength + id.size() + body.size();
            int32_t n_total_len = htonl(h_total_len);

            std::string ret;
            ret.reserve(h_total_len);
            ret.append((char *)&n_total_len, lenFieldsLength);
            ret.append((char *)&mtype, mtypeFieldsLength);
            ret.append((char *)&idlen, idlenFieldsLength);
            ret.append(id);
            ret.append(body);
            return ret;
        }
    };

    class ProtocolFactory
    {
    public:
        template <typename... Args>
        static BaseProtocol::ptr create(Args &&...args)
        {
            return std::make_shared<LVProtocol>(std::forward<Args>(args)...);
        }
    };

    class MuduoConnection : public BaseConnection
    {
    private:
        BaseProtocol::ptr _protocol;
        muduo::net::TcpConnectionPtr _conn;

    public:
        using ptr = std::shared_ptr<MuduoConnection>;
        MuduoConnection(const muduo::net::TcpConnectionPtr &conn,
                        const BaseProtocol::ptr &protocol) : _protocol(protocol),
                                                             _conn(conn) {}
        virtual void send(const BaseMessage::ptr &msg) override
        {
            _conn->send(_protocol->serialize(msg));
        }
        virtual void shutdown() override
        {
            _conn->shutdown();
        }
        virtual bool connected() override
        {
            return _conn->connected();
        }
    };
    class ConnectionFactory
    {
    public:
        template <typename... Args>
        static BaseConnection::ptr create(Args &&...args)
        {
            return std::make_shared<MuduoConnection>(std::forward<Args>(args)...);
        }
    };
    /*
        Muduo服务
    */
    class MuduoServer : public BaseServer
    {
    private:
        const size_t maxDataSize = (1 << 16);
        BaseProtocol::ptr _protocol;
        muduo::net::EventLoop _baseloop;
        muduo::net::TcpServer _server;
        std::mutex _mutex;
        std::unordered_map<muduo::net::TcpConnectionPtr, BaseConnection::ptr> _conns;

    public:
        using ptr = std::shared_ptr<MuduoServer>;
        MuduoServer(int port) : _server(&_baseloop,
                                        muduo::net::InetAddress("0.0.0.0", port),
                                        "MuduoServer",
                                        muduo::net::TcpServer::kReusePort),
                                _protocol(ProtocolFactory::create()) {}
        virtual void start() override
        {
            _server.setConnectionCallback(std::bind(&MuduoServer::onConnection, this, std::placeholders::_1));
            _server.setMessageCallback(std::bind(&MuduoServer::onMessage, this,
                                                 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
            _server.start();  // 先开始监听
            _baseloop.loop(); // 开始死循环事件监控
        }

    private:
        void onConnection(const muduo::net::TcpConnectionPtr &conn)
        {
            if (conn->connected())
            {
                LOG(INFO, "连接建立");
                auto muduo_conn = ConnectionFactory::create(conn, _protocol);
                {
                    std::unique_lock<std::mutex> lock(_mutex);
                    _conns.insert(std::make_pair(conn, muduo_conn));
                }
                if (_cb_connection)
                    _cb_connection(muduo_conn);
            }
            else
            {
                LOG(INFO, "连接断开");
                BaseConnection::ptr muduo_conn;
                {
                    std::unique_lock<std::mutex> lock(_mutex);
                    auto it = _conns.find(conn);
                    if (it == _conns.end())
                    {
                        return;
                    }
                    muduo_conn = it->second;
                    _conns.erase(it->first);
                }
                if (_cb_close)
                    _cb_close(muduo_conn);
            }
        }
        void onMessage(const muduo::net::TcpConnectionPtr &conn, muduo::net::Buffer *buf, muduo::Timestamp)
        {
            LOG(INFO, "连接有数据到来，开始处理！");
            BaseBuffer::ptr base_buf = BufferFactory::create(buf);
            while (true)
            {
                // 检查缓冲区数据是否够一条消息
                if (_protocol->canProcessed(base_buf) == false)
                {
                    // 数据异常
                    if (base_buf->readableSize() > this->maxDataSize)
                    {
                        conn->shutdown();
                        LOG(ERROR, "缓冲区中数据过大！");
                        return;
                    }
                    break;
                }

                // 获取一条消息
                BaseMessage::ptr msg;
                bool ret = _protocol->onMessage(base_buf, msg);
                if (ret == false)
                {
                    conn->shutdown();
                    LOG(ERROR, "缓冲区中数据错误！");
                    return;
                }

                // 获取连接
                BaseConnection::ptr base_conn;
                {
                    std::unique_lock<std::mutex> lock(_mutex);
                    auto it = _conns.find(conn);
                    if (it == _conns.end())
                    {
                        conn->shutdown();
                        LOG(DEBUG, "连接断开");
                        return;
                    }
                    base_conn = it->second;
                }
                // 执行回调函数
                if (_cb_message)
                {
                    _cb_message(base_conn, msg);
                }
            }
        }
    };
    class ServerFactory
    {
    public:
        template <typename... Args>
        static BaseServer::ptr create(Args &&...args)
        {
            return std::make_shared<MuduoServer>(std::forward<Args>(args)...);
        }
    };

    class MuduoClient : public BaseClient
    {
    private:
        const size_t maxDataSize = (1 << 16);
        BaseProtocol::ptr _protocol;
        BaseConnection::ptr _conn;
        muduo::CountDownLatch _downlatch;
        muduo::net::EventLoopThread _loopthread;
        muduo::net::EventLoop *_baseloop;
        muduo::net::TcpClient _client;

    public:
        using ptr = std::shared_ptr<MuduoClient>;
        MuduoClient(const std::string &sip, int sport) : _baseloop(_loopthread.startLoop()),
                                                         _client(_baseloop,
                                                                 muduo::net::InetAddress(sip, sport),
                                                                 "MuduoClient"),
                                                         _downlatch(1),
                                                         _protocol(ProtocolFactory::create()) {}
        virtual void connect() override
        {
            LOG(INFO, "设置回调函数，连接服务器");
            _client.setConnectionCallback(std::bind(&MuduoClient::onConnection, this, std::placeholders::_1));
            // 设置连接消息的回调
            _client.setMessageCallback(std::bind(&MuduoClient::onMessage, this,
                                                 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));

            // 连接服务器
            _client.connect();
            // 阻塞防止连接没有建立成功（异步非阻塞）
            _downlatch.wait();
            LOG(INFO, "连接服务器成功！");
        }

        virtual void shutdown() override
        {
            return _client.disconnect();
        }

        virtual bool send(const BaseMessage::ptr &msg) override
        {
            if (connected() == false)
            {
                LOG(INFO, "连接已断开！");
                return false;
            }
            _conn->send(msg);
            return true;
        }

        virtual BaseConnection::ptr connection() override
        {
            return _conn;
        }

        virtual bool connected()
        {
            return (_conn && _conn->connected());
        }

    private:
        void onMessage(const muduo::net::TcpConnectionPtr &conn, muduo::net::Buffer *buf, muduo::Timestamp)
        {
            LOG(INFO, "连接有数据到来，开始处理！");
            BaseBuffer::ptr base_buf = BufferFactory::create(buf);
            while (true)
            {
                // 检查缓冲区数据是否够一条消息
                if (_protocol->canProcessed(base_buf) == false)
                {
                    // 数据异常
                    if (base_buf->readableSize() > this->maxDataSize)
                    {
                        conn->shutdown();
                        LOG(ERROR, "缓冲区中数据过大！");
                        return;
                    }

                    // 数据不足-退出循环
                    break;
                }

                // 获取一条消息
                BaseMessage::ptr msg;
                bool ret = _protocol->onMessage(base_buf, msg);
                if (ret == false)
                {
                    conn->shutdown();
                    LOG(ERROR, "缓冲区中数据错误！");
                    return;
                }

                // 执行回调函数
                if (_cb_message)
                    _cb_message(_conn, msg);
            }
        }
        void onConnection(const muduo::net::TcpConnectionPtr &conn)
        {
            if (conn->connected())
            {
                LOG(INFO, "连接建立！");
                // 计数--，为0时唤醒阻塞
                _conn = ConnectionFactory::create(conn, _protocol);
                _downlatch.countDown();
            }
            else
            {
                LOG(INFO, "连接断开！");
                _conn.reset();
            }
        }
    };
    class ClientFactory
    {
    public:
        template <typename... Args>
        static BaseClient::ptr create(Args &&...args)
        {
            return std::make_shared<MuduoClient>(std::forward<Args>(args)...);
        }
    };
}